package view.swing.tiles;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import model.iview.ITile;

import view.swing.tiles.TileDragDroppable.AllowedState;

public class Placeur extends MouseAdapter {

    public static TileDragDroppable currentTile = null;

    public void drop(TileDragDroppable source, TileDragDroppable dest) {
        if (source == dest) {
            return;
        }

        if (source == null || dest == null || !source.hasTileHere()) {
            return;
        }

        if (dest.hasTileHere()) { // Il faut inverser les deux
            ITile tmp = dest.drag();
            dest.drop(source.drag());
            source.drop(tmp);
        } else {
            dest.drop(source.drag());
            dest.setSource(source.getSource() != null ? source.getSource()
                    : source);
        }

        source.setSelected(false);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (!(e.getSource() instanceof TileDragDroppable)) {
            return;
        }

        TileDragDroppable tileDD = ((TileDragDroppable) e.getSource());
        
        if (tileDD.getAllowedState() == AllowedState.NONE) {
            return;
        }

        if ((e.getButton() != MouseEvent.BUTTON1 || e.getClickCount() > 1)
                && tileDD.getSource() != null && tileDD.hasTileHere()) {
            if (tileDD.getTile().isOldJoker()) {
                tileDD.getTile().clearJokerValue();
            }
            tileDD.getSource().drop(tileDD.drag());
            tileDD.setSource(null);
            return;
        }

        if (tileDD == currentTile) {
            currentTile.setSelected(false);
            currentTile = null;
            return;
        }

        switch (tileDD.getAllowedState()) {
        case BOTH:
            if (currentTile != null) {
                drop(currentTile, tileDD);
                currentTile = null;
            } else {
                currentTile = tileDD;
                currentTile.setSelected(true);
            }
            break;
        case DRAG:
            if (tileDD.hasTileHere()) {
                if (currentTile != null) {
                    return;
                }
                currentTile = tileDD;
                tileDD.setSelected(true);
            }
            break;
        case DROP:
            drop(currentTile, tileDD);
            currentTile = null;
            break;
        }
    }
    
    public static void reset() {
        if (currentTile != null) {
            currentTile.setSelected(false);
            currentTile = null;
        }
        
    }
}